<template>
    <div class="box-content">
        <div class="navigation">管理员账号列表</div>
        <!--搜索-->
        <div class="mt-3">
            <el-row :gutter="10">
                <el-col :span="24">
                    <el-input type="text" style="width:200px;margin-right: 10px" size="small" v-model="search.inputName" :clearable="true" placeholder="输入关键字(昵称或邮箱)"></el-input>
                    <el-button type="primary" size="small" @click="onSearch">查询</el-button>
                    <el-button type="primary" size="small" @click="createAccount">新增</el-button>
                </el-col>
            </el-row>
        </div>
        <!--表格-->
        <div class="mt-3">
            <el-table
                    :data="userData"
                    v-loading="loading"
                    align="center"
                    :element-loading-text="loadText"
                    :header-cell-style="tableHeaderColor"
                    stripe
                    style="width: 100%">
                <el-table-column
                        prop="id"
                        align="center"
                        label="编号"
                        width="100"
                >
                </el-table-column>
                <el-table-column
                        prop="username"
                        align="center"
                        width="200"
                        label="昵称">
                </el-table-column>
                <el-table-column
                        prop="mobile"
                        align="center"
                        label="手机号"
                        width="110">
                </el-table-column>
                <el-table-column
                        prop="email"
                        align="center"
                        width="200"
                        label="邮箱">
                </el-table-column>
                <el-table-column
                        align="center"
                        label="绑定景区"
                        width="200">
                    <template slot-scope="scope">
                        <span >{{scope.row['tr_name']}}<i class="el-icon-edit edit_icon" @click="openBind(scope.row)"></i></span>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="status"
                        align="center"
                        label="状态">
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.status"
                               :active-value="1"
                               :inactive-value="0"
                                @change=changeStatus(scope.row)></el-switch>
                    </template>

                </el-table-column>
                <el-table-column
                        prop="last_ip"
                        label="登录ip"
                        align="center"
                        width="120">
                </el-table-column>
                <el-table-column
                        label="登录时间"
                        align="center"
                        width="100">
                    <template slot-scope="scope">
                        <div align="center">{{scope.row['last_login']?scope.row['last_login'].slice(0, 11):'无'}}</div>
                        <div align="center">{{scope.row['last_login']?scope.row['last_login'].slice(11 ):'无'}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作"
                        align="center"
                        fixed="right"
                        width="160">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="primary"
                                @click="handleEdit(scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="mt-3 float-right">
                <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageInfo.current_page"
                        :page-size="pageInfo.per_page"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageInfo.total">
                </el-pagination>
            </div>
        </div>
        <!--新增对话框-->
        <el-dialog :title="dialog.title"
                   :visible.sync="dialogFormVisible"
                   :close-on-click-modal="false"
                   width="600px">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px" v-loading="loadingDialig">
                <el-form-item label="账号分类" prop="type">
                    <el-radio-group v-model="form.type">
                        <el-radio :label="2">后台账号</el-radio>
                        <!--<el-radio :label="3">前台账号</el-radio>-->
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="昵称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入昵称" style="width: 450px;"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone" v-if="!dialog.isEdit">
                    <el-input v-model="form.phone" placeholder="请输入手机号" style="width: 450px;"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password" v-if="!dialog.isEdit">
                    <el-input v-model="form.password" placeholder="请输入登录密码" style="width: 450px;"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password1" v-if="dialog.isEdit">
                    <el-input v-model="form.password1" placeholder="请输入登录密码" style="width: 450px;"></el-input>
                    <div style="color: red;font-size: 12px;line-height: 1;">若不填密码则为原密码不变化</div>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" style="width: 450px;"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" v-if="!dialog.isEdit" :loading="loadingCreate"
                           @click="submitCostomer('form')">{{loadingCreate?'创建中':'点击创建'}}
                </el-button>
                <el-button type="primary" v-if="dialog.isEdit" :loading="loadingCreate" @click="submitCostomer('form')">
                    {{loadingCreate?'修改中':'点击修改'}}
                </el-button>
            </div>
        </el-dialog>
        <el-dialog title="绑定景区"
                   :visible.sync="dialogFormVisible1"
                   :close-on-click-modal="false"
                   width="600px">
            <el-form :model="form1" :rules="rules1" ref="form1" label-width="100px" v-loading="loadingDialig1">
                <el-form-item label="景区绑定" prop="bingValue">
                    <el-select v-model="form1.bingValue" placeholder="请选择景区绑定" style="width: 400px;">
                        <el-option
                                v-for="item in jingQuData"
                                :key="item.id"
                                :label="item.tr_name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible1 = false">取 消</el-button>
                <el-button type="primary" :loading="loadingCreate1"
                           @click="submitCostomer1('form1')">{{loadingCreate1?'绑定中':'点击绑定'}}
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "accountList",
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    var r = /^[^\u4e00-\u9fa5]+$/
                    if (!r.test(value)) {
                        callback(new Error('密码不能为中文!'));
                    }
                    if (value.length < 6) {
                        callback(new Error('密码长度在 6 到 18 个字符!'));
                    }
                    callback();
                }
            };
            var phoneValid = (rule, value, callback) => {
                let phoneReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
                if (!value) {
                    callback(new Error('请输入手机号'))
                }
                if (!phoneReg.test(value)) {
                    callback(new Error('请输入正确的手机号码'))
                }
                callback()
            };
            return {

                isClick: false,
                jingQuData:[],
                baseId: null,
                baseId1: null,
                inputName: '',
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1
                },
                loadText: '数据加载中',
                userData: [],
                searchStr: '',
                search: {
                    inputName:'',
                    type:''
                },
                loading: false,
                loadingCancel: false,
                loadingDialig: false,
                loadingDialig1: false,
                loadingCreate: false,
                loadingCreate1: false,
                dialogFormVisible: false,
                dialogFormVisible1: false,
                form: {
                    type: 2,
                    name: '',
                    phone: '',
                    email: '',
                    password: '',
                    password1: ''
                },
                form1:{
                    bingValue:''
                },
                dialog: {
                    title: '',
                    isEdit: false
                },
                typeOption: [
                    {name: '前台',type: '3'},
                    {name: '后台',type: '2'}
                ],
                rules1:{
                    bingValue: []
                },
                rules: {
                    phone: [
                        {validator: phoneValid, trigger: 'change'}
                    ],
                    password: [
                        {validator: validatePass, trigger: 'change'}
                    ],
                    email: [
                        {type: 'email', message: '请输入正确的邮箱地址', trigger: 'change'},
                        { required: true, message: '请输入邮箱地址', trigger: 'change' },
                    ],
                    type: [
                        { required: true, message: '请选择账号分类', trigger: 'change' },
                    ]
                }
            }
        },
        watch: {
            dialogFormVisible: function (val) {
                if (!val) {
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.$refs['form'].resetFields();
                }
            }
        },
        created() {
            this.getJingQuList();
            this.getAccountList();
        },
        methods: {
            openBind(val) {
                this.form1.bingValue = val.tr_id;
                this.baseId1 = val.id;
                this.dialogFormVisible1 = true;
            },
            getJingQuList() {
                this.$http.get('api/auth/tourismResort')
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.jingQuData = result.data.data;
                        } else {
                            this.$message.warning(result.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            changeName(val) {
                this.search.inputName = val;

            },
            createAccount() {
                this.dialog.title = '注册用户';
                this.dialog.isEdit = false;
                this.dialogFormVisible = true;
            },
            changeStatus(val) {
                let params = {
                    status: val.status
                };
                this.$http.put('api/auth/admin/' + val.id, params)
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.$message({
                                type: 'success',
                                message: result.msg,
                                during: 1000
                            });
                        } else {
                            this.$message.warning(result.msg);
                        }
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            getAccountList() {
                this.loading = true;
                this.$http.get('api/system/admin/list?type=2' + this.searchStr, {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.userData = result.data.data;
                            this.pageInfo.total = result.data.total;
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onSearch() {
                this.searchStr = "";
                if (this.search.inputName) {
                    this.addConStr();
                    this.searchStr += `&keyword=${this.search.inputName}`;
                }
                // if (this.search.type) {
                //     this.addConStr();
                //     this.searchStr += `type=${this.search.type}`;
                // }
                this.pageInfo.current_page = 1;
                this.getAccountList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            submitCostomer(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.creatShanHu();
                    } else {
                        return false;
                    }
                });
            },submitCostomer1(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.bindJingQu();
                    } else {
                        return false;
                    }
                });
            },
            bindJingQu() {
                this.loadingCreate1 = true;
                let params ={
                    user_id: this.baseId1,
                    tr_id: this.form1.bingValue
                };
                this.$http.post('api/system/bindTourismResort', params)
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.$message({
                                type: 'success',
                                message: result.msg,
                                during: 1000
                            });
                            this.getAccountList();
                            this.dialogFormVisible1 = false;
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loadingCreate1 = false;
                    })
                    .catch((err) => {
                        this.loadingCreate1 = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            creatShanHu() {
                this.loadingCreate = true;
                let params;
                if (this.dialog.isEdit) {
                    if (this.form.password1) {
                        params={
                            type: this.form.type,
                            username:this.form.name,
                            // mobile: this.form.phone,   // 编辑时电话不能更改
                            password:this.form.password1,
                            email:this.form.email
                        }
                    } else {
                        params={
                            type: this.form.type,
                            username:this.form.name,
                            // mobile: this.form.phone,   // 编辑时电话不能更改
                            email:this.form.email
                        }
                    }

                    this.$http.put('api/auth/admin/' + this.baseId, params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                                this.dialogFormVisible = false;
                            } else {
                                this.$message.warning(result.msg);
                            }
                            this.loadingCreate = false;
                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                } else {
                    params={
                        type: this.form.type,
                        username:this.form.name,
                        mobile: this.form.phone,
                        password:this.form.password,
                        email:this.form.email
                    };
                    this.$http.post('api/system/admin/save', params)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                                this.dialogFormVisible = false;
                            } else {
                                this.$message.warning(result.msg);
                            }
                            this.loadingCreate = false;

                        })
                        .catch((err) => {
                            this.loadingCreate = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }

            },
            handleEdit(val) {
                this.baseId = val.id;
                this.dialog.title = '编辑账户';
                this.dialog.isEdit = true;
                this.dialogFormVisible = true;
                this.loadingDialig = true;
                this.$http.get('api/system/admin/list/' + val.id)
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.form.name = result.data.username;
                            this.form.tr_name = result.data.tr_name;
                            this.form.phone = result.data.mobile;
                            this.form.email = result.data.email;
                            this.form.type = Number(result.data.type);
                        } else {
                            this.$message.warning(result.msg);
                        }
                        this.loadingDialig = false;
                    })
                    .catch((err) => {
                        this.loadingDialig = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleDelete(val) {
                this.$confirm('此操作将永久删除账户,不可修复, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete('api/auth/admin/' + val.id)
                        .then((result) => {
                            if (result.status_code == 200) {
                                this.$message({
                                    type: 'success',
                                    message: result.msg,
                                    during: 1000
                                });
                                this.getAccountList();
                            } else {
                                this.$message.warning(result.msg);
                            }
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getAccountList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getAccountList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            },
        }
    }
</script>

<style lang="less">
    .edit_icon:hover{
        color: #545cff;
        cursor: pointer;
    }
    .check-children {
        cursor: pointer;
    }

    .check-children:hover {
        color: #409EFF;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
    }

    .avatar {
        width: 100px;
        height: 100px;
        display: block;
    }
</style>